vendor-slug.js ➔ toggleSlugModification   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
dl 0
loc 9
rs 10
1
(function ($) {
2
    'use strict';
3
4
    $.fn.extend({
5
        vendorSlugGenerator: function () {
6
            let timeout;
7
8
            $('[name*="vendor"][name*="[name]"]').on('input', function() {
9
                clearTimeout(timeout);
10
                let element = $(this);
11
12
                timeout = setTimeout(function() {
13
                    updateSlug(element);
14
                }, 1000);
15
            });
16
17
            $('.toggle-vendor-slug-modification').on('click', function(e) {
18
                e.preventDefault();
19
                toggleSlugModification($(this), $(this).siblings('input'));
20
            });
21
22
            function updateSlug(element) {
23
                let slugInput = element.parents().find('[name*="[slug]"]');
24
                let loadableParent = slugInput.parents('.field.loadable');
25
26
                if ('readonly' === slugInput.attr('readonly')) {
27
                    return;
28
                }
29
30
                loadableParent.addClass('loading');
31
32
                $.ajax({
33
                    type: "GET",
34
                    url: slugInput.attr('data-url'),
35
                    data: { name: element.val() },
36
                    dataType: "json",
37
                    accept: "application/json",
38
                    success: function(data) {
39
                        slugInput.val(data.slug);
40
                        if (slugInput.parents('.field').hasClass('error')) {
41
                            slugInput.parents('.field').removeClass('error');
42
                            slugInput.parents('.field').find('.sylius-validation-error').remove();
43
                        }
44
                        loadableParent.removeClass('loading');
45
                    }
46
                });
47
            }
48
49
            function toggleSlugModification(button, slugInput) {
50
                if (slugInput.attr('readonly')) {
51
                    slugInput.removeAttr('readonly');
52
                    button.html('<i class="unlock icon"></i>');
53
                } else {
54
                    slugInput.attr('readonly', 'readonly');
55
                    button.html('<i class="lock icon"></i>');
56
                }
57
            }
58
        }
59
    });
60
})(jQuery);
61
62
(function($) {
63
    $(document).ready(function () {
64
        $(this).vendorSlugGenerator();
65
    });
66
})(jQuery);
67